package com.skmc.okcashbag.common;

import android.app.Activity;

import com.skmc.okcashbag.model.MyCardInfo;

public class MyCardList {
	
	private static MyCardInfo[] cards;
	
	public static void loadCards(Activity obj) throws FileException{
		cards = FileMyCard.read(obj);
	}
	
	public static int size(){
		if(cards == null) return 0;
		
		return cards.length;
	}
	
	public static void add(Activity obj, MyCardInfo card) throws FileException{
		if(size() == 0){
			cards = new MyCardInfo[]{card};
			FileMyCard.write(obj, card.getCard_no() +","
					+ card.getBz_card_cd()+","
					+ card.getBz_card_cd_name()+","
					+ card.getGrp_id());
			return;
		}
		
		MyCardInfo[] mcs = new MyCardInfo[cards.length+1];
		System.arraycopy(cards, 0, mcs, 1, cards.length);
		mcs[0] = card;
		
		FileMyCard.add(obj, card);
		cards = mcs;
	}
	
	public static void delete(Activity obj, int delIdx) throws FileException{
		if(size() == 1){
			cards = null;
			FileMyCard.write(obj, "");
			return;
		}
		
		MyCardInfo[] mcs = new MyCardInfo[cards.length-1];
		int idx = 0;
		for(int i = 0; i < size(); i++){
			if(i == delIdx) continue;
			mcs[idx] = cards[i];
			idx++;
		}
		cards = mcs;
		
		FileMyCard.delete(obj, mcs);
	}
	
	public static MyCardInfo get(int idx){
		if(size() == 0) return null;
		return cards[idx];
	}
	
	public static MyCardInfo[] getAlls(){
		return cards;
	}
	
	public static MyCardInfo getByCode(String cardCode){
		MyCardInfo card = null;
		for(int i = 0; i < size(); i++){
			if(cards[i].getBz_card_cd().equals(cardCode)){
				card = cards[i];
				break;
			}
		}
		return card;
	}
	
	public static MyCardInfo getByNum(String cardNum){
		MyCardInfo card = null;
		for(int i = 0; i < size(); i++){
			if(cards[i].getCard_no().equals(cardNum)){
				card = cards[i];
				break;
			}
		}
		return card;
	}
	
	public static void swap(Activity obj, int src, int dsc) throws FileException{
		int cardCnt = size();
		MyCardInfo[] newObjs = new MyCardInfo[cardCnt];
		
		boolean isSrcBack = src < dsc;
		int p1 = Math.min(src, dsc);
		int p2 = Math.max(src, dsc);
		

		for(int i = 0; i < p1; i++){
			newObjs[i] = cards[i];
		}
		
		if(isSrcBack){
			for(int i = p1; i < p2; i++){
				newObjs[i] = cards[i+1];
			}
			newObjs[p2] = cards[src];
		}else{
			newObjs[p1] = cards[src];
			for(int i = p1+1; i <= p2; i++){
				newObjs[i] = cards[i-1];
			}
		}
		
		for(int i = p2+1; i < cardCnt; i++){
			newObjs[i] = cards[i];
		}
		
		System.arraycopy(newObjs, 0, cards, 0, cards.length);
		
		StringBuffer sb = new StringBuffer();
		for(int i = 0; i < cardCnt; i++){
			if(i != 0) sb.append("|");
			sb.append(cards[i].getCard_no()).append(",")
			.append(cards[i].getBz_card_cd()).append(",")
			.append(cards[i].getBz_card_cd_name()).append(",")
			.append(cards[i].getGrp_id());
		}
		
		FileMyCard.write(obj, sb.toString());
	}

}

